package com.attendancesystem.controller;


import com.attendancesystem.model.User;
import com.attendancesystem.service.UserService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import javax.servlet.annotation.WebServlet;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "AddUserController", value = "/AddUserController")
public class AddUserController extends HttpServlet {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
//        response.setContentType("text/html;charset=UTF-8");
        response.setContentType("application/json;charset=UTF-8"); // 增加字符集定义
        BufferedReader reader = request.getReader();
        JsonNode rootNode = objectMapper.readTree(reader);
        String username = rootNode.get("username").asText();
        String password = rootNode.get("password").asText();
        String role = rootNode.get("role").asText();
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setRole(User.UserRole.valueOf(role));
        UserService userService = new UserService();
        if(userService.addUser(user)){
            out.print("{\"status\":\"success\"}");
        }else{
            out.print("{\"status\":\"failed\"}");
        }




    }
}
